package com.leyou.cart;

import com.leyou.cart.service.CartService;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @package com.leyou.cart
 * @description: 购物车监听
 * @author: 许超越
 * @date 2019/7/14 21:31
 * @version: V1.0
 */
@Component
@Slf4j
public class CartListener {

    /**
     * 队列名称
     */
    private static final String CART_GOODS_DOWN_QUEUE = "cart.goods.down.queue";
    /**
     * 购物车付款订单移出发送消息的交换机名称
     */
    private static final String CART_EXCHANGE_NAME = "ly.cart.exchange";
    /**
     * 购物车付款订单移出购物车路由名称
     */
    private static final String CART_DOWN_KEY = "ly.cart.key";

    @Autowired
    private CartService cartService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = CART_GOODS_DOWN_QUEUE, durable = "true"),
            exchange = @Exchange(name = CART_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = CART_DOWN_KEY))
    public void listenCart(Map<String, String> msg) {
        try {
            //接收消息调用方法删除
            String jsonIdList = msg.remove("skuIdList");
            String userId = msg.remove("userId");
            List<Long> skuIdList = JsonUtils.toList(jsonIdList, Long.class);
            if (CollectionUtils.isEmpty(skuIdList)) {
                throw new RuntimeException("下单商品id集合为空！");
            }
            cartService.deleteCartByIds(skuIdList, userId);
        } catch (NumberFormatException e) {
            log.error("获取下单消息失败！原因：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
